<?php

if (!defined('IN_XLP')) {
    exit('Access Denied!');
}

/**
 * Description of pagesAction
 *
 * @author Administrator
 */
class pagesAction extends commonAction {

    function __construct() {
        parent::__construct();
        parent::_checkLogin();
    }

    public function index() {
        $p = $this->_getid('p', 1);
        $q = $this->_get('q');
        $where = array('city_id' => admin::$adminInfo['city_id']);
        if ($q) {
            $where['LIKE'] = array('title' => $q);
        }
        $rs = M('page')->where($where)->page($p)->order('sort DESC,id desc')->findAll();
        $this->assign(array('rs' => $rs, 'total' => M('page')->getTotal(), 'p' => $p, 'q' => $q));
        $this->display();
    }

    public function add() {
        $this->display();
    }

    public function edit() {
        $id = $this->_getid('id', '');
        if (!$id) {
            showError('参数丢失');
        }
        $rs = M('page')->where(array('id' => $id, 'city_id' => admin::$adminInfo['city_id']))->find();
        if (!$rs) {
            showError('内容不存在');
        }
        $this->assign(array('rs' => $rs));
        $this->display();
    }

    public function post() {
        $objDate = $this->_getpostData();
        $id = M('page')->insert($objDate);
        $this->JsonReturn('ok', $id, 1);
    }

    public function save() {
        $id = $this->_postid('id');
        if (!$id) {
            showError('参数丢失');
        }
        $rs = M('page')->where(array('id' => $id, 'city_id' => admin::$adminInfo['city_id']))->find();
        if (!$rs) {
            showError('内容不存在');
        }
        $objData = $this->_getpostData();
        M('page')->update($objData, array('id' => $id));
        $this->delPageData($id);
        $this->JsonReturn('ok', null, 1);
    }

    public function delete() {
        parent::_checkLogin();
        $id = $this->_postid('id');
        if (!$id) {
            showError('参数丢失');
        }
        M('page')->delete(array('id' => $id, 'city_id' => admin::$adminInfo['city_id']));
        $this->delPageData($id);
        $this->JsonReturn('ok', null, 1);
    }

    //接收字段列表
    private function _getpostData() {
        parent::_checkLogin();
        $list = array(
            'title' => '',
            'city_id' => admin::$adminInfo['city_id'],
            'content' => '',
            'sort' => 0,
            'infotime' => 0
        );
        $objData = array();
        foreach ($list as $k => $v) {
            if ($k == 'content') {
                $objData[$k] = $this->_postContent('content');
            } else {
                $objData[$k] = $this->_post($k, $v);
            }
        }
        $objData['infotime'] = TIME;
        $objData['sort'] = intval($objData['sort']);
        if (!$objData['title']) {
            return $this->JsonReturn('标题为必填');
        }
        return $objData;
    }

    private function delPageData($id) {
        return F('page/detail_' . $id, null);
    }

}
